package com.nb.sse.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.nb.sse.model.UnReadMsgVO;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.nb.sse.entity.Message;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@Service
public class MessageService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final Map<Integer, SseEmitter> emitters = new ConcurrentHashMap<>();

    public void addEmitter(Integer userId, SseEmitter emitter) {
        emitters.put(userId, emitter);
    }

    public void removeEmitter(Integer userId) {
        emitters.remove(userId);
    }

    public void publish(UnReadMsgVO msgVO) {
        String msg = JSONObject.toJSONString(msgVO);

        UnReadMsgVO msgVO2 = JSONObject.parseObject(msg,UnReadMsgVO.class);

        stringRedisTemplate.convertAndSend("message:channel", msg);
    }

    /**
     * 总的来说，这段代码在应用程序启动并准备就绪后，
     * 订阅一个名为"message:channel"的Redis频道，
     * 并在接收到消息时，将消息发送给名为"zhangsan666"的SseEmitter。
     *
     */
    @EventListener(ApplicationReadyEvent.class)
    public void subscribe() {
        stringRedisTemplate.getConnectionFactory().getConnection().subscribe(
                (message, pattern) -> {
                    // 在这里处理接收到的消息
                    String content =  new String(message.getBody());
                    System.out.println("content========="+content);
                    UnReadMsgVO msgVO = JSONObject.parseObject(content, UnReadMsgVO.class);

                    SseEmitter emitter = emitters.get(msgVO.getUserId());
                    if (emitter != null) {
                        try {
                            emitter.send(msgVO.getCount());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                },
                "message:channel".getBytes()
        );
    }
}